<template>
	<div>
		<el-form ref="form" label-width="100px">
			<el-form-item label="监测时间">
				<el-date-picker type="date" placeholder="选择日期" v-model="params.completeTime">
				</el-date-picker>
			</el-form-item>

			<el-form-item label="监测结果">
				<el-select v-model="params.result" placeholder="请选择监测结果">
					<el-option label="正常" value="NORMAL"></el-option>
					<el-option label="不正常" value="ABNORMAL"></el-option>
				</el-select>
			</el-form-item>

			<el-form-item label="报告开始时间">
				<el-date-picker type="date" placeholder="选择日期" v-model="params.reportStartTime">
				</el-date-picker>
			</el-form-item>

			<el-form-item label="报告结束时间">
				<el-date-picker type="date" placeholder="选择日期" v-model="params.reportEndTime">
				</el-date-picker>
			</el-form-item>
			<el-form-item label="监测内容">
				<div class="displayFlexBet">
					<div style="flex: 2;"></div>
					<div style="flex: 2;" class="mr5">频次1</div>
					<div style="flex: 2;" class="mr5">频次2</div>
					<div style="flex: 2;" class="mr5">频次3</div>
					<div style="flex: 2;" class="mr5">平均值</div>
					<div style="flex: 1;">单位</div>
				</div>
				<div class="displayFlexBet mb10" v-for="(item,index) in params.pollutionList" :key="index">
					<div style="flex: 2;">{{item.pollutionName}}</div>
					<div style="flex: 2;" class="mr5">
						<el-input v-model="item.firstValue" type="number"></el-input>
					</div>
					<div style="flex: 2;" class="mr5">
						<el-input v-model="item.secondValue" type="number"></el-input>
					</div>
					<div style="flex: 2;" class="mr5">
						<el-input v-model="item.thirdValue" type="number"></el-input>
					</div>
					<div style="flex: 2;" class="mr5">
						<el-input v-model="item.pollutionValue"></el-input>
					</div>
					<div style="flex: 1;">{{item.unitCode}}</div>
				</div>
			</el-form-item>

			<el-form-item label="文件">
				<div style="display: flex;">
					<el-upload accept=".doc,.docx,.pdf,.ppt,.pptx,.xlsx" :limit="1" :multiple="false"
						:file-list="upload.fileList" action="#" drag :auto-upload="false" :on-change="changeFile"
						:on-remove="removeFile" :on-exceed="uploadFileOver">
						<i class="el-icon-upload"></i>
						<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					</el-upload>

					<el-select v-model="params.fileId" class="ml20" placeholder="关联报告">
						<el-option v-for="(item,index) in linkFileList" :key="index" :label="item.fileName"
							:value="item.fileId"></el-option>
					</el-select>
				</div>
			</el-form-item>

			<el-form-item label="异常文件说明" v-if="params.result == 'ABNORMAL'">
				<el-upload accept=".doc,.docx,.pdf,.ppt,.pptx" :limit="1" :multiple="false"
					:file-list="upload.abnormalFileList" action="#" drag :auto-upload="false" :on-change="changeFile2"
					:on-remove="removeFile2" :on-exceed="uploadFileOver">
					<i class="el-icon-upload"></i>
					<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
				</el-upload>
			</el-form-item>

		</el-form>
		<div slot="footer" class="dialog-footer" style="text-align: center!important;margin-top: 20px;">
			<el-button type="primary" size="small" @click="save()" :loading="isLoading">确 定</el-button>
			<el-button size="small" @click="cancle">取 消</el-button>
		</div>
	</div>
</template>

<script>
	import $ from 'jquery'

	let that
	let APPKEY = '5da5441f62e48aedc7a3853ffc75c2db';
	let PRODID = 'gf';
	let UPLOAD_ACTION = '/upload';
	let VIEW_ACTION = '/view';
	let REMOVE_ACTION = '/remove';
	let IMGURL = 'https://www.weifeibangbang.com/wfbb-webupload/service/sys/file/upload';
	export default {
		name: 'app',
		components: {},
		props: ['selectItem', 'optionType', 'type'],
		data() {
			return {
				isLoading: false,
				params: {
					categoryMainId: '',
					ticketId: '',
					itemId: '',
					pollutionList: [],
				},
				upload: {
					file: '',
					fileList: [],
					abnormalFile: '',
					abnormalFileList: [],
					visible: false,
					params: {
						id: '', // 档案id
						categoryItemId: '', // 子类id
						title: '', // 标题
						fileId: '', // 文件id
						abnormalFileId: '',
						remark: '', // 注释
						endTime: '', // 到期时间
						isQualified: '1', //是否合格
						isLong: false,
						receiveTime: '',
						completeTime: '',
						result: '',

					},
				},
				linkFileList: []
			}
		},
		watch: {
			'params.pollutionList': {
				handler(n, o) {
					for (let item of n) {
						if (item.firstValue && item.secondValue && item.thirdValue){
							item.pollutionValue = ((Number(item.firstValue) + Number(item.secondValue) + Number(item.thirdValue)) / 3).toFixed(3)
						} 
					}
				},
				deep: true,
			},

		},
		created: function() {},
		mounted: function() {
			that = this
			that.params.categoryMainId = that.getQueryString("categoryMainId")
			that.params.ticketId = that.$store.state.token
			that.params.itemId = that.getQueryString("itemId")

			if (that.optionType == "edit") {
				that.getEffectiveDocumentRecordByCustomerId()
				that.getSurveyResultById()
			}
		},
		methods: {

			getSurveyResultById() {
				that.ajax({
					url: '/gasOutlet/getSurveyResultById?ticketId=' + that.params.ticketId,
					data: {
						id: that.selectItem.id,
					},
					contentType: 'application/x-www-form-urlencoded',
					success: function(result) {
						that.params = result.data
						if (result.data.fileId) {
							that.upload.fileList = [{
								name: result.data.fileName,
								percentage: 0,
								raw: "File",
								size: 0,
								status: "ready",
								uid: 1667201692291,
								url: result.data.fileId
							}]
						}

						that.$forceUpdate()
					},
				})

				that.ajax({
					url: '/gasOutlet/getSurveyFileList?ticketId=' + that.params.ticketId,
					data: {
						id: that.selectItem.id,
					},
					contentType: 'application/x-www-form-urlencoded',
					success: function(result) {
						that.linkFileList = result.data
					},
				})
			},

			//获取最新档案列表
			getEffectiveDocumentRecordByCustomerId() {
				that.ajax({
					url: '/document/getEffectiveDocumentRecordByCustomerId?ticketId=' + that.params
						.ticketId,
					data: JSON.stringify({
						categoryItemId: that.selectItem.id,
					}),
					contentType: 'application/json',
					dataType: 'json',
					method: 'POST',
					success: function(result) {
						if (result.status == 1) {
							if (result.data) {
								that.upload.params.id = result.data.id
								that.upload.params.title = result.data.title
								that.upload.params.fileId = result.data.fileId
								that.upload.params.remark = result.data.remark
								that.upload.params.endTime = result.data.endTime
								//that.params.isQualified = '1' //是否合格
								that.upload.params.receiveTime = result.data.receiveTime
								that.upload.fileList = [{
									name: result.data.title + ".pdf",
									percentage: 0,
									raw: "File",
									size: 0,
									status: "ready",
									uid: 1667201692291,
									url: result.data.fileId
								}]
								that.$forceUpdate()
							} else {
								that.$emit("success", true)
								return that.$message({
									message: '暂未上传文件',
									type: 'warning'
								});
							}
						}
					}
				});
			},

			cancle() {
				that.$emit("cancle", true)
			},

			uploadFileOver(files, fileList) {
				return this.$message({
					message: '请上传文件数量已超出，点击删除后重新上传文件',
					type: 'warning'
				});
			},

			changeFile: function(file, fileList) {
				var _this = this;
				file.url = URL.createObjectURL(file.raw);
				_this.upload.fileList = fileList
				_this.upload.file = file;
			},

			removeFile() {
				this.upload.fileList = []
				this.upload.file = ''
			},

			changeFile2: function(file, fileList) {
				var _this = this;
				file.url = URL.createObjectURL(file.raw);
				_this.upload.abnormalFileList = fileList
				_this.upload.abnormalFile = file;
			},

			removeFile2() {
				this.upload.abnormalFileList = []
				this.upload.abnormalFile = ''
			},

			uploadFile: function(callback) {
				var _this = this;

				if (that.params.fileId) {
					return callback(that.params.fileId)
				}
				if (that.optionType == "edit" && that.upload.file == '') {
					callback(that.upload.params.fileId)
				} else {
					var formdata = new FormData()
					formdata.append("file", _this.upload.file.raw);
					formdata.append("appKey", APPKEY);
					formdata.append("businessCode", that.randomChar(19));
					formdata.append("prodID", PRODID);
					$.ajax({
						url: IMGURL + '/upload',
						data: formdata,
						type: 'POST',
						dataType: 'json',
						contentType: false,
						processData: false,
						success: function(result) {
							var fileId = result.message.fileID;
							that.params.fileId = fileId
							callback(fileId);
						},
						error: function() {}
					})
				}
			},


			uploadFile2: function(callback) {
				var _this = this;

				if (that.optionType == "edit" && that.upload.abnormalFile == '') {
					callback(that.upload.params.abnormalFileId)
				} else {
					var formdata = new FormData()
					formdata.append("file", _this.upload.abnormalFile.raw);
					formdata.append("appKey", APPKEY);
					formdata.append("businessCode", that.randomChar(19));
					formdata.append("prodID", PRODID);
					$.ajax({
						url: IMGURL + '/upload',
						data: formdata,
						type: 'POST',
						dataType: 'json',
						contentType: false,
						processData: false,
						success: function(result) {
							var fileId = result.message.fileID;
							callback(fileId);
						},
						error: function() {}
					})
				}
			},

			randomChar: function(l) {
				var x = "0123456789qwertyuioplkjhgfdsazxcvbnm";
				var tmp = "";
				var timestamp = new Date().getTime();
				for (var i = 0; i < l; i++) {
					tmp += x.charAt(Math.ceil(Math.random() * 100000000) % x.length);
				}
				return timestamp + tmp;
			},


			save() {
				let that = this
				let apiName
				if (that.optionType != 'edit') {
					if (that.upload.file == '' && !that.params.fileId) {
						return this.$message({
							message: '请上传文件',
							type: 'warning'
						});
					} else if (that.params.completeTime == '' || that.params.completeTime == null) {
						return this.$message({
							message: '请选择完成时间',
							type: 'warning'
						});
					} else if (that.params.result == '' || that.params.result == null) {
						return this.$message({
							message: '请选择结果',
							type: 'warning'
						});
					}
				}

				that.params.ticketId = that.$store.state.token
				if (that.type == 'gas') apiName = '/gasOutlet/submitGasOutletSurvey?ticketId=' + that.params.ticketId
				if (that.type == 'water') apiName = '/waterOutlet/submitWaterOutletSurvey?ticketId=' + that.params.ticketId

				that.isLoading = true

				//return console.log(that.params)
				that.uploadFile(function(fileId) {
					//that.uploadFile2(function(fileId2) {
					that.ajax({
						url: apiName,
						dataType: 'json',
						contentType: 'application/json',
						data: JSON.stringify(that.params),
						success: function(result) {
							that.isLoading = false
							if (result.data) {
								that.upload = that.$options.data().upload

								that.$emit("success", true)
								return that.$message({
									message: '保存成功',
									type: 'success'
								});
							} else {
								return that.$message({
									message: result.infoList[0],
									type: 'error'
								});
							}

						}
					})
					//})

				})
			},

		},
	}
</script>

<style>
</style>